using Apollo.AST;
using Apollo.EvaluatorUtils;
using Apollo.LexerUtils;
using Apollo.ParserUtils;
using Apollo.TokenUtils;
using Newtonsoft.Json;
using System.Text;
using System.Text.Json.Serialization;
using static System.Collections.Specialized.BitVector32;

namespace Apollo
{
    public partial class FmMain : Form
    {
        public FmMain()
        {
            InitializeComponent();
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            var lexer = new Lexer(txtProgram.Text);
            while (true)
            {
                var token = lexer.Next_Token();
                listBox1.Items.Add(token);
                if (token.Type == TokenType.EOF)
                {
                    return;
                }
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            Lexer lexer = new Lexer(txtProgram.Text);
            Parser parser = new Parser(lexer);
            var section = parser.Parse_Program();
            string jsonString = "";
            foreach (var item in section.m_statements)
            {
                jsonString += JsonConvert.SerializeObject(item);
                jsonString += "\r\n";
            }
            txtLexer.Text = jsonString;
            using (FileStream fs = new("..\\..\\..\\PaserResult.json", FileMode.OpenOrCreate))
            {
                var content = Encoding.UTF8.GetBytes(jsonString);
                fs.Write(content, 0, content.Length);
            }

            Evaluator evaluator = new();
            var result = evaluator.Eval(section);
            listBox1.Items.Add(result);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}